package cpe.hapa.authentication;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.ServletException;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

import cpe.hapa.authentication.Authenticate;
import cpe.hapa.dao.UserDAO;
import cpe.hapa.model.User;
 

public class SessionHandler {
	private static int totalActiveSessions=0;
	private static int SESSION_TIMEOUT=600; // en seconde
	private static Map<Key, Date> properties = new HashMap<Key, Date>();
	 
	public static int getTotalActiveSession(){
		return totalActiveSessions;
	}
	
	public static void addSession(Key key) throws NumberFormatException, ParseException, EntityNotFoundException {
		if(!properties.containsKey(key)) {
			User user = UserDAO.getByKey(key);
			if(user != null) {
				user.setDateConnexion(new Date());
				UserDAO.update(user);
				totalActiveSessions++;
				System.out.println("Session créée");
			} else {
				return;
			}
			
		}
		properties.put(key, new Date());
	}
	
	public static Boolean Contains(Key key) {
		if(properties.containsKey(key)) {
			properties.put(key, new Date());
			return true;
		}
		
		return false;
	}

	public static void deleteSession(Key key) throws NumberFormatException, ParseException, EntityNotFoundException {
		if(!properties.containsKey(key)) {
			return;
		}
		
		long lastConnectionTime;
		long currentTime = new Date().getTime();
		long sessionTime;
		
		User user = UserDAO.getByKey(key);
		if(user != null) {
			lastConnectionTime = user.getDateConnexion().getTime();
			sessionTime = (long) ((currentTime - lastConnectionTime)/1000);
			user.setDureeConnexion(sessionTime);
			UserDAO.update(user);
			properties.remove(key);
			totalActiveSessions--;
			System.out.println("Session de "+ user.getLogin() + " détruite");
		}
	}
	
	public static void checkAllSessions() throws NumberFormatException, ParseException, EntityNotFoundException {
		long lastTime;
		long currentTime = new Date().getTime();
		long sessionTime;
		List<Key> sessionsToDelete = new ArrayList<>();
		
		for(Entry<Key,Date> session : properties.entrySet()) {
			lastTime = session.getValue().getTime();
			sessionTime = (long) (currentTime - lastTime)/1000;
			
			if( sessionTime > SESSION_TIMEOUT) {
				sessionsToDelete.add(session.getKey());
			}
		}
		
		for(Key k : sessionsToDelete) {
			deleteSession(k);
		}
	}
}

